package com.csx;

/**
 * @author 陈胤训
 * @date 2019/5/29 19:22
 * Utils: Intellij Idea
 * Description:
 */
public class Strategy {

    public static void main(String[] args) {
        Cat[] arr = {new Cat(3, 3), new Cat(1, 1), new Cat(5, 5)};
        DataSorter ds = new DataSorter();
        ds.sort(arr);
        for(int i = 0; i < arr.length; i++){
            System.out.println(arr[i]);
        }
    }
}

class DataSorter{//用于排序的工具类
    public void sort(Object[] arr){//参数类型为Object
        for(int i = arr.length - 1; i > 0; i--){
            for(int j = 0; j < i; j++){
                Comparable c1 = (Comparable) arr[j];//先转为Comparable类型
                Comparable c2 = (Comparable) arr[j + 1];
                if(c1.CompareTo(c2) == 1)//背后已经转换为使用Comparator的定义的规则进行比较
                    swap(arr, j, j  + 1);
            }
        }
    }

    private void swap(Object[] arr, int i, int j){
        Object temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}

class Cat implements Comparable{
    private int age;
    private int weight;
    private Comparator comparator = new CatAgeComparator();//默认持有年龄比较器

    public Cat(int age, int weight) {
        this.age = age;
        this.weight = weight;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }

    @Override
    public int CompareTo(Object o) {
        return comparator.Compare(this, o);//调用比较器比较而不是直接在此写比较法则
    }

    // get / set / toString ...
}

interface Comparable{
    public int CompareTo(Object o);
}

interface Comparator{
    public int Compare(Object o1, Object o2);
}

//用户自己定义的, 按照猫的年龄比较大小的比较器
class CatAgeComparator implements Comparator{
    @Override
    public int Compare(Object o1, Object o2) {
        Cat c1 = (Cat) o1;
        Cat c2 = (Cat) o2;
        if(c1.getAge() > c2.getAge()) return 1;
        else if(c1.getAge() < c2.getAge()) return -1;
        else return 0;
    }
}

//按照猫的体重比较大小的比较器
class CatWeightComparator implements Comparator{
    @Override
    public int Compare(Object o1, Object o2) {
        Cat c1 = (Cat) o1;
        Cat c2 = (Cat) o2;
        if(c1.getWeight() > c2.getWeight()) return 1;
        else if(c1.getWeight() < c2.getWeight()) return -1;
        else return 0;
    }


}

